package com.example.tellwin.utils;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Log打印日志类
 * Date&Time: 2015-10-12 11:23
 */
public class LogUtil {
    public static boolean islog = true;
    public static String tag = "FW";
    public static final String SAVE_DIR = "sdcard/fw/";
    private static final String LOG_SAVE_PATH = SAVE_DIR + "log_fw/"; // 日志保存目录
    private static final String TAG = "log_fw";
    private static final boolean isSaveLog = true; // 是否把保存日志到SD卡中

    /**
     * @param message
     */
    public static void d(String message) {
        if (islog) {
            message = message == null ? "为空" : message;
            Log.d(tag, message);
        }
    }

    /**
     * @param message
     */
    public static void e(String message) {
        if (islog) {
            message = message == null ? "为空" : message;
//            Log.e(tag, message);

            int max_str_length = 4000 - tag.length();
            //大于4000时
            while (message.length() > max_str_length) {
                Log.e(tag, message.substring(0, max_str_length));
                message = message.substring(max_str_length);
            }
            //剩余部分
            Log.e(tag, message);
        }
    }

    /**
     * @param message
     */
    public static void e(String tag,String message) {
        if (islog) {
            message = message == null ? "为空" : message;
            Log.e(tag, message);
        }
    }

    /**
     * @param message
     */
    public static void i(String message) {
        if (islog) {
            message = message == null ? "为空" : message;
            Log.e(tag, message);
        }
    }

    /**
     * 保存崩溃错误日志信息,只记录第一个报错
     * @param throwable
     */
    /*public static void saveCrashLogInfo(final Throwable throwable){
        if(isSaveLog){

            TaskManager.getInstance().post(new Runnable() {
                @Override
                public void run() {

                    long currentTime = System.currentTimeMillis();
                    long lastTime = DataSave.create(DataSave.save_type.save_to_sdcard).readLong("log_save_time");

                    //LogUtil.i("saveCrashLogInfo...currentTime:" + currentTime + ", lastTime:" + lastTime);

                    if (currentTime - lastTime < 1000 * 10) {
                        return;
                    }

                    DataSave.create(DataSave.save_type.save_to_sdcard).saveLong("log_save_time", currentTime);

                    //LogUtil.i("saveCrashLogInfo........." + throwable.toString());

                    //打印错误日志
                    throwable.printStackTrace();

                    final String tagName = getFunctionName();

                    //保存错误日志
                    write(time() + TAG + tagName + " [CRASH起始点] --> "
                            + getStackTraceString(throwable) + "\n");
                }
            });
        }
    }*/

    /**
     * 获取捕捉到的异常的字符串
     * @param tr
     * @return
     */
    public static String getStackTraceString(Throwable tr)
    {
        if (tr == null)
        {
            return "";
        }

        Throwable t = tr;
        while (t != null)
        {
            if (t instanceof UnknownHostException)
            {
                return "";
            }
            t = t.getCause();
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        tr.printStackTrace(pw);
        return sw.toString();
    }

    /**
     * 标识每条日志产生的时间
     * @return
     */
    private static String time()
    {
        return "["+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(
                System.currentTimeMillis())) + "] ";
    }

    /**
     * 获取日志文件路径
     * @return
     */
    public static String getFile()
    {
        File sdDir = null;

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED))
            sdDir = Environment.getExternalStorageDirectory();

        File cacheDir = new File(LOG_SAVE_PATH);
        if (!cacheDir.exists())
            cacheDir.mkdir();

        File filePath = new File(cacheDir + File.separator + date() + ".txt");

        LogUtil.e("程序发生崩溃, 保存当前错误日志信息, 文件路径:" + filePath);

        return filePath.toString();
    }

    /**
     * 以年月日作为日志文件名称
     * @return
     */
    private static String date()
    {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date(System
                .currentTimeMillis()));
    }

    /**
     * 保存到日志文件
     * @param content
     */
    public static synchronized void write(String content)
    {
        try
        {
            FileWriter writer = new FileWriter(getFile(), true);
            writer.write(content);
            writer.close();

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private static String getFunctionName() {
        StackTraceElement[] sts = Thread.currentThread().getStackTrace();

        if (sts == null) {
            return "";
        }

        for (StackTraceElement st:sts) {
            if (st.isNativeMethod()) {
                continue;
            }

            if (st.getClassName().equals(Thread.class.getName())) {
                continue;
            }

            if (st.getClassName().equals(LogUtil.class.getName())) {
                continue;
            }

            return "["+Thread.currentThread().getId()+": "+st.getFileName()+" : "+st.getLineNumber()+" : "+st.getMethodName()+"]---";
        }

        return "";
    }

}
